<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { getHorizonData, getVerticalData } from "@/api/reportList";

// 获取当前时间，并计算一星期前的时间
const currentTime = new Date();
const oneWeekAgo = new Date(currentTime.getTime() - 7 * 24 * 60 * 60 * 1000);

// 格式化日期为 YYYY - MM - DD 形式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 搜索表单数据，设置初始值
const searchForm = ref({
  begin: formatDate(oneWeekAgo),
  end: formatDate(currentTime)
});

// 图表数据
const chartData = ref({
  horizontal: {
    nameList: [],
    numberList: []
  },
  vertical: {
    dateList: [],
    turnoverList: []
  }
});

// 图表实例
let chart1 = null;
let chart2 = null;

// 加载图表数据
const loadCharts = () => {
  // 横向柱状图数据获取和初始化
  getHorizonData(searchForm.value.begin, searchForm.value.end).then(res => {
    chartData.value.horizontal.nameList = res.data.nameList;
    chartData.value.horizontal.numberList = res.data.numberList;

    if (!chart1) {
      chart1 = echarts.init(document.getElementById('userCount1'));
    }

    const option = {
      yAxis: {
        type: 'category',
        data: chartData.value.horizontal.nameList
      },
      xAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'bar',
          data: chartData.value.horizontal.numberList,
          itemStyle: {
            color: '#3398DB'
          },
          label: {
            show: true,
            position: 'right'
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      }
    };

    chart1.setOption(option);
  });

  // 垂直柱状图数据获取和初始化
  getVerticalData(searchForm.value.begin, searchForm.value.end).then(res => {
    chartData.value.vertical.dateList = res.data.dateList;
    chartData.value.vertical.turnoverList = res.data.turnoverList;

    if (!chart2) {
      chart2 = echarts.init(document.getElementById('userCount2'));
    }

    const option1 = {
      xAxis: {
        data: chartData.value.vertical.dateList
      },
      yAxis: {},
      series: [
        {
          type: 'bar',
          data: chartData.value.vertical.turnoverList,
          itemStyle: {
            color: '#91cc75'
          }
        }
      ],
      tooltip: {
        trigger: 'axis'
      }
    };

    chart2.setOption(option1);
  });

  // 确保 DOM 渲染完成后触发 resize，保证图表填满容器
  nextTick(() => {
    chart1?.resize();
    chart2?.resize();
  });
};

// 搜索按钮处理
const handleSearch = () => {
  loadCharts();
};

// 重置按钮处理，恢复为初始值（当前时间往前推一星期和当前时间）
const handleReset = () => {
  const currentTimeReset = new Date();
  const oneWeekAgoReset = new Date(currentTimeReset.getTime() - 7 * 24 * 60 * 60 * 1000);
  searchForm.value.begin = formatDate(oneWeekAgoReset);
  searchForm.value.end = formatDate(currentTimeReset);
  loadCharts();
};

onMounted(() => {
  loadCharts();
});

onUnmounted(() => {
  // 销毁图表实例，释放资源
  if (chart1) {
    chart1.dispose();
    chart1 = null;
  }
  if (chart2) {
    chart2.dispose();
    chart2 = null;
  }
});
</script>

<template>
  <div class="container">
    <!-- 顶部标题 -->
    <div id="title">数据统计</div>

    <el-form :inline="true" class="search-form">
      <el-form-item label="起始时间：">
        <el-date-picker
            v-model="searchForm.begin"
            type="date"
            placeholder="选择起始时间"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束时间：">
        <el-date-picker
            v-model="searchForm.end"
            type="date"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">清空</el-button>
      </el-form-item>
    </el-form>

    <h1 class="page-title">商品信息统计</h1>
    <div class="chart-container">
      <!-- 新增 fixed-chart 类确保宽高 -->
      <div id="userCount1" class="chart-item fixed-chart"></div>
      <div id="userCount2" class="chart-item fixed-chart"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 24px;
  background-color: #f9fafc;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 标题区域 */
#title {
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 12px;
  display: flex;
  align-items: center;
}

/* 搜索表单 */
.search-form {
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;

  display: flex;
  flex-wrap: wrap;
  gap: 16px;

  .el-form-item {
    margin-bottom: 0;

    .el-input,
    .el-select,
    .el-date-picker {
      width: 220px;

      .el-input__inner {
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        transition: all 0.3s;

        &:focus {
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          border-color: #409eff;
        }
      }
    }
  }

  .el-button {
    height: 36px;
    padding: 0 16px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
    }
  }
}

/* 图表容器 */
.chart-container {
  display: flex;
  flex-wrap: nowrap;
  gap: 24px;
  margin-top: 24px;
  justify-content: space-between;

  .chart-item {
    flex: 0 0 calc(50% - 12px);
    min-width: 0;
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    overflow: hidden;
  }
}

/* 关键：强制图表容器宽高 */
.fixed-chart {
  width: 100% !important;
  height: 350px !important;
  min-width: 300px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chart-container {
    flex-direction: column;

    .fixed-chart {
      width: 100% !important;
      height: 300px !important;
    }
  }
}
</style>